package dao

import (
	"gin-demo/model"
	"gin-demo/tool"
	"log"
)

type MemberDao struct {
	*tool.Orm
}

func (md *MemberDao) QueryMemberById(userId int) *model.Member {
	var member model.Member
	if _, err := md.Where("id = ?", userId).Get(&member); err != nil {
		return nil
	}
	return &member
}

// 更新指定用户的头像
func (md *MemberDao) UpdateMemberAvatar(userId int64, fileName string) int64 {

	member := model.Member{Avatar: fileName}
	result, err := md.Where(" id = ? ", userId).Update(&member)
	if err != nil {
		log.Fatalln(err.Error())
		return 0
	}
	return result
}

// 用户名和密码查询
func (md *MemberDao) Query(name, password string) *model.Member {
	var member model.Member

	password = tool.EncoderSha256(password)
	_, err := md.Where(" user_name = ? and password = ?", name, password).Get(&member)
	if err != nil {
		log.Fatalln(err.Error())
		return nil
	}
	return &member
}

// 手机号码+验证码的正确性验证
func (md *MemberDao) ValidateSmsCode(phone, code string) *model.SmsCode {
	var sms model.SmsCode

	if _, err := md.Where(" phone = ? and code = ? ", phone, code).Get(&sms); err != nil {
		log.Fatalln(err.Error())
	}

	return &sms

}

func (md *MemberDao) QueryByPhone(phone string) *model.Member {
	var member model.Member

	if _, err := md.Where(" mobile = ?", phone).Get(&member); err != nil {
		log.Fatalln(err.Error())
	}

	return &member
}

func (md *MemberDao) InsertMember(member model.Member) int64 {
	retsult, err := md.InsertOne(&member)

	if err != nil {
		log.Fatalln(err.Error())
	}

	return retsult
}

func (md *MemberDao) InsertCode(sms model.SmsCode) int64 {

	retsult, err := md.InsertOne(&sms)

	if err != nil {
		log.Fatalln(err.Error())
	}

	return retsult

}
